<?php
// +----------------------------------------------------------------------
// | OneThink [ WE CAN DO IT JUST THINK IT ]
// +----------------------------------------------------------------------
// | Copyright (c) 2013 http://www.onethink.cn All rights reserved.
// +----------------------------------------------------------------------
// | Author: 麦当苗儿 <zuojiazi@vip.qq.com> <http://www.zjzit.cn>
// +----------------------------------------------------------------------

namespace Admin\Controller;
use User\Api\UserApi as UserApi;
use Think\Model;

/**
 * 后台首页控制器
 * @author 麦当苗儿 <zuojiazi@vip.qq.com>
 */
class InventoryController extends AdminController {
    /***
     *实时库存列表
     */
    public function inventoryrealtime(){
        $map = array();
        if(I('BIN')!==""){
            $map['BIN'] = array('like','%'.I('BIN').'%');
        }
        if(I('pname')!==""){
            $map['pname'] = array('like','%'.I('pname').'%');
        }
        if(I('classify')!==""){
            $map['BIN'] = array('like',I('classify').'%');
        }
        $model = M('vinventory');
        $res = $model->where($map)->select();
        $total = count($res);
        if (isset($REQUEST['r'])) {
            $listRows = (int) $REQUEST['r'];
        } else {
            $listRows = C('LIST_ROWS') > 0 ? C('LIST_ROWS') : 10;
        }
        $page = new \Think\Page($total, $listRows, $REQUEST);

        if ($total > $listRows) {
            $page->setConfig('theme', '%FIRST% %UP_PAGE% %LINK_PAGE% %DOWN_PAGE% %END% %HEADER%');
        }
        $p = $page->show();
        $classify = M('Material_classify')->where(array('status'=>1))->select();

        $this->assign('_page', $p ? $p : '');
        $this->assign('_total', $total);
        $this->assign("_list",$res);
        $this->assign("_classify",$classify);
        $this->title = "实时库存";
        $this->display();
    }
    /**
     * 入库
     * @author James
     * 2016-01-15
     */
    public function inadd(){
        if(IS_POST){
            $model = M('Inventory_warn');
            $trans = true;
            $BIN_array = I('BIN');
            $cnt_array = I('cnt');
            $have_days_array = I('have_days');
//            $material_array = I('material');
            for ($i = 0; $i < count($BIN_array); $i++) {
                if ($BIN_array[$i] == ""  || $cnt_array[$i] == "" || $have_days_array[$i] == "") {
                    $this->error("入库商品信息不能为空");
                }
            }
            $model->startTrans();
            for ($i = 0; $i < count($BIN_array); $i++) {
                $d = $have_days_array[$i];
                $fruit_classify_no = get_no_by_tag($BIN_array[$i],'fruit_classify_no');//获取水果分类编号
                $pname_no = get_no_by_tag($BIN_array[$i],'pname_no');//获取商品名编号
                $info = getperiod($fruit_classify_no);//获取水果分类的周期
                if($d>=10){
                    $w = date("Ymd",time()).$d;
                }else{
                    $w = date("Ymd",time())."0".$d;
                }
                $batchMap['BIN'] = $BIN_array[$i];
                $batchMap['warn_batch'] = $w;
                if($model->where($batchMap)->find()){
                    if(!$model->where($batchMap)->setInc('cnt',$cnt_array[$i])){
                        $trans = false;
                    }
                }else{
                    $period2 =  date("Ymd",strtotime("+".($info['per2_time']-$have_days_array[$i])." day"));
                    $period3 =  date("Ymd",strtotime("+".($info['per3_time']-$have_days_array[$i])." day"));
                    $batchData['BIN']= $BIN_array[$i];
                    $batchData['warn_batch']= $w;
                    $batchData['cnt']= $cnt_array[$i];
                    $batchData['pname']= get_name_by_id($pname_no,'Material_pname','pname_no','pname');
                    $batchData['have_days']= $d;
                    $batchData['per2_time']= $period2;
                    $batchData['per3_time']= $period3;
                    if(!M("Inventory_warn")->add($batchData)){
                        $trans = false;
                    }
                }
                $dataList[] = array(
                    'batch' => date("Ymd",time()),
                    'cnt' => $cnt_array[$i],
                    'warn_batch' => $w,
                    'UID' => UID,
                    'createAt' => time(),
                    'BIN' => $BIN_array[$i]);
            }
            if($trans){
                $model->commit();
                M('Inventory_inlist')->addAll($dataList);
            }else{
                $model->rollback();
            }
            $this->success('入库成功！', U('inlist'));
        }else{
            $prolist = M("Material_product")->where('status=1')->select();
            $this->assign('product', json_encode($prolist) );
            $this->title = "入库";
            $this->display('inadd');
        }
    }
    public function inlist() {
        $where = "where 1 = 1 ";
        if(I('date')){
            $where.= "and batch like '%".I('date')."%'";
        }
        $Model = new Model();
        $sql = "select batch ,count(BIN) as count1  from gr_inventory_inlist ".$where."  group by batch";
        $list1 = $Model->query($sql);
        $total = count($list1);
        if (isset($REQUEST['r'])) {
            $listRows = (int) $REQUEST['r'];
        } else {
            $listRows = C('LIST_ROWS') > 0 ? C('LIST_ROWS') : 10;
        }

        $page = new \Think\Page($total, $listRows, $REQUEST);

        if ($total > $listRows) {
            $page->setConfig('theme', '%FIRST% %UP_PAGE% %LINK_PAGE% %DOWN_PAGE% %END% %HEADER%');
        }
        $p = $page->show();

        $this->assign('_page', $p ? $p : '');
        $this->assign('_total', $total);
        $this->assign('_list', $list1);
        $this->title = '入库记录';
        $this->display();
    }
    public function indetail() {
        $batch = I('batch');
        if($batch){
            $map['batch'] = array('like', '%' . (string) $batch . '%');
        }

        $map['status']  =   1;

        $list = $this->lists('Inventory_inlist', $map,'createAt desc');

        $this->assign('_list', $list);
        $this->title = '入库明细';
        $this->display();
    }
    /**
     * 出库
     * @author James
     * 2016-01-14
     */
    public function outadd(){
        if(IS_POST){
            $cnt_array = I('cnt');
            $warnbatch_array = I('warn_batch');
            $BIN_array = I('BIN');
            $c = count($BIN_array);
            $model = M('Inventory_warn');
            $trans = true;
            for ($i = 0; $i < $c; $i++) {
                if ($cnt_array[$i] == "" || $warnbatch_array[$i] == "") {
                    $this->error("出库信息不完整");
                }
            }
            $model->startTrans();
            for ($i = 0; $i < $c; $i++) {
                $map['BIN'] = $BIN_array[$i];
                $map['warn_batch'] = $warnbatch_array[$i];
                if(!$model->where($map)->setDec('cnt',$cnt_array[$i])){
                    $trans = false;
                }
                $dataList[] = array(
                    'BIN'=>$BIN_array[$i],
                    'warn_batch'=>$warnbatch_array[$i],
                    'cnt'=>$cnt_array[$i],
                    'UID'=>UID,
                    'createAt'=>time(),
                    'batch' => date("Ymd",time())
                );
            }
            if($trans){
                $model->commit();
                M('Inventory_outlist')->addAll($dataList);
            }else{
                $model->rollback();
            }
            $this->success("操作成功");
        }else{
            $map['cnt']  =   array('gt',0);
            $prolist = M("Vinventory")->where($map)->select();
            foreach($prolist as $key => $val){
                $spec = M('Material_product')->where(array('BIN'=>$val['BIN']))->getField('spec');
                $prolist[$key]['spec'] = $spec;
            }
            $map2['cnt'] = array('gt',0);
            $inventory_warn = M("Inventory_warn")->where($map2)->select();
            $this->assign( 'product', json_encode($prolist) );
            $this->assign( 'inventory', json_encode($inventory_warn) );
            $this->assign( '_prolist', $prolist );
            $this->title = '出库';
            $this->display();

        }
    }
    public function outlist() {
        $where = "where 1 = 1 ";
        if(I('date')){
            $where.= "and batch like '%".I('date')."%'";
        }
        $Model = new Model();
        $sql = "select batch ,count(BIN) as count1  from gr_inventory_outlist  ".$where." group by batch";
        $list1 = $Model->query($sql);
        $total = count($list1);
        if (isset($REQUEST['r'])) {
            $listRows = (int) $REQUEST['r'];
        } else {
            $listRows = C('LIST_ROWS') > 0 ? C('LIST_ROWS') : 10;
        }

        $page = new \Think\Page($total, $listRows, $REQUEST);

        if ($total > $listRows) {
            $page->setConfig('theme', '%FIRST% %UP_PAGE% %LINK_PAGE% %DOWN_PAGE% %END% %HEADER%');
        }
        $p = $page->show();
        $this->assign('_page', $p ? $p : '');
        $this->assign('_total', $total);
        $this->assign('_list', $list1);
        $this->title = '出库记录';
        $this->display();
    }
    public function outdetail() {
        $batch = I('batch');
        if($batch){
            $map['batch'] = array('like', '%' . (string) $batch . '%');
        }

        $map['status']  =   1;

        $list = $this->lists('Inventory_outlist', $map,'createAt desc');

        $this->assign('_list', $list);
        $this->title = '出库明细';
        $this->display();
    }
    /***
     * 盘点
     */
    public function checkinventory(){
        if(IS_POST){
            $checkcnt_array = I('check_cnt');
            $warnbatch_array = I('warn_batch');
            $BIN_array = I('BIN');
            $reason_array = I('reason');
            $c = count($BIN_array);
            $model = M('Inventory_warn');
            $trans = true;
            for ($i = 0; $i < $c; $i++) {
                if ($checkcnt_array[$i] == "" || $warnbatch_array[$i] == ""||$BIN_array[$i] == "") {
                    $this->error("盘点信息不完整");
                }
            }
            $model->startTrans();
            for ($i = 0; $i < $c; $i++) {
                $map['BIN'] = $BIN_array[$i];
                $map['warn_batch'] = $warnbatch_array[$i];
                $data['cnt'] = $checkcnt_array[$i];
                if($model->where($map)->save($data)===false){
                    $trans= false;
                }
                $dataList[] = array(
                    'BIN'=>$BIN_array[$i],
                    'warn_batch'=>$warnbatch_array[$i],
                    'checkcnt'=>$checkcnt_array[$i],
                    'reason'=>$reason_array[$i],
                    'UID'=>UID,
                    'createAt'=>time(),
                    'batch' => date("Ymd",time())
                );
            }
            if($trans){
                $model->commit();
                M('Inventory_check')->addAll($dataList);
            }else{
                $model->rollback();
            }
            $this->success("操作成功");
        }else{

            $prolist = M("Vinventory")->select();
            foreach($prolist as $key => $val){
                $spec = M('Material_product')->where(array('BIN'=>$val['BIN']))->getField('spec');
                $prolist[$key]['spec'] = $spec;
            }
            $map2['status'] = array('eq',1);
            $inventory_warn = M("Inventory_warn")->where($map2)->select();
            $this->assign( 'product', json_encode($prolist) );
            $this->assign( 'inventory', json_encode($inventory_warn) );
            $this->assign( '_prolist', $prolist );
            $this->title = '盘点';
            $this->display();

        }
    }
    public function checklist() {
        $where = "where 1 = 1 ";
        if(I('date')){
            $where.= "and batch like '%".I('date')."%'";
        }
        $Model = new Model();
        $sql = "select batch ,count(BIN) as count1  from gr_inventory_check  ".$where." group by batch";
        $list1 = $Model->query($sql);
        $total = count($list1);
        if (isset($REQUEST['r'])) {
            $listRows = (int) $REQUEST['r'];
        } else {
            $listRows = C('LIST_ROWS') > 0 ? C('LIST_ROWS') : 10;
        }

        $page = new \Think\Page($total, $listRows, $REQUEST);

        if ($total > $listRows) {
            $page->setConfig('theme', '%FIRST% %UP_PAGE% %LINK_PAGE% %DOWN_PAGE% %END% %HEADER%');
        }
        $p = $page->show();
        $this->assign('_page', $p ? $p : '');
        $this->assign('_total', $total);
        $this->assign('_list', $list1);
        $this->title = '盘点记录';
        $this->display();
    }
    public function checkdetail() {
        $batch = I('batch');
        if($batch){
            $map['batch'] = array('like', '%' . (string) $batch . '%');
        }

        $map['status']  =   1;

        $list = $this->lists('Inventory_check', $map,'createAt desc');

        $this->assign('_list', $list);
        $this->title = '盘点明细';
        $this->display();
    }
    /**
     * 实时库存导出
     * @author James
     * 2016-02-18
     */
    public function kcExport() {
        $where = "";
        if(I('BIN')!==""){
            $where.="and BIN like '%".I('BIN')."%' ";
//            $map['BIN'] = array('like','%'.I('BIN').'%');
        }
        if(I('pname')!==""){
            $where.="and pname like '%".I('pname')."%' ";
//            $map['pname'] = array('like','%'.I('pname').'%');
        }
        if(I('classify')!==""&&I('BIN')==""){
            $where.="and BIN like '".I('BIN')."%' ";
//            $map['BIN'] = array('like',I('classify').'%');
        }
        
        $sql = "select a.BIN,a.cnt,a.pname from gr_vinventory a where 1=1 ".$where." ORDER BY a.cnt desc";
        $Model = new Model();
        $data = $Model->query($sql);
        if ($data){
            add_erp_log('Inventory','vinventory','库存表','export','导出库存表');
            $i = 0;
            foreach($data as $key => $val){
                $data[$i]['spec'] = get_name_by_id($val['BIN'],'Material_product','BIN','spec');
                $data[$i]['classify'] = get_name_by_id($val['BIN'],'Material_product','BIN','classify');
                $i++;
            }
            //导入PHPExcel类库，因为PHPExcel没有用命名空间，只能inport导入
            import("Org.Util.PHPExcel");
            import("Org.Util.PHPExcel.Writer.Excel5");
            import("Org.Util.PHPExcel.IOFactory.php");

            $filename = "output_order_excel";

            $headArr = array("BIN","数量", "商品名称","规格","货别");

            $title = "实时库存列表";
            $this->getExcel($filename, $headArr, $data, $title);
        }else{
            $this->error("没有可导出的数据！");
        }
    }
    private function getExcel($fileName, $headArr, $data, $title) {
        //对数据进行检验
        if (empty($data) || !is_array($data)) {
            //die("data must be a array");
        }
        //检查文件名
        if (empty($fileName)) {
            exit;
        }
        // H:i:s
        $date = date("Y_m_d_H_i_s", time());
        //$date = date("Y_m_d",time());
        $fileName .= "_{$date}.xls";

        //创建PHPExcel对象，注意，不能少了\
        $objPHPExcel = new \PHPExcel();
        $objProps = $objPHPExcel->getProperties();

        //第一列设置报表时间范围
        $key = ord("A");
        $colum = chr($key);
        $objPHPExcel->setActiveSheetIndex(0)->setCellValue($colum . '1', $title);


        //第二列设置报表列头
        $key = ord("A");
        foreach ($headArr as $v) {
            $colum = chr($key);
            $objPHPExcel->setActiveSheetIndex(0)->setCellValue($colum . '2', $v);
            $key += 1;
        }

        $column = 3;
        $objActSheet = $objPHPExcel->getActiveSheet();
        foreach ($data as $key => $rows) { //行写入
            $span = ord("A");
            foreach ($rows as $keyName => $value) {// 列写入
                $j = chr($span);
                $objActSheet->setCellValue($j . $column, $value);
                $objActSheet->getColumnDimension('a')->setWidth(20);
                $objActSheet->getColumnDimension('b')->setWidth(20);
                if (count($headArr) == 12){
                    $objActSheet->getColumnDimension('d')->setWidth(20);
                    $objActSheet->getColumnDimension('h')->setWidth(20);
                    $objActSheet->getColumnDimension('i')->setWidth(20);
                    $objActSheet->getColumnDimension('j')->setWidth(30);
                    $objActSheet->getColumnDimension('l')->setWidth(100);
                }else{
                    $objActSheet->getColumnDimension('g')->setWidth(20);
                    $objActSheet->getColumnDimension('h')->setWidth(20);
                    $objActSheet->getColumnDimension('i')->setWidth(30);
                    $objActSheet->getColumnDimension('j')->setWidth(30);
                    $objActSheet->getColumnDimension('k')->setWidth(100);
                }
                $span++;
            }
            $column++;
        }

        $fileName = iconv("utf-8", "gb2312", $fileName);
        //重命名表
        // $objPHPExcel->getActiveSheet()->setTitle('test');
        //设置活动单指数到第一个表,所以Excel打开这是第一个表
        $objPHPExcel->setActiveSheetIndex(0);
        header('Content-Type: application/vnd.ms-excel');
        header("Content-Disposition: attachment;filename=\"$fileName\"");
        header('Cache-Control: max-age=0');

        $objWriter = \PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
        $objWriter->save('php://output'); //文件通过浏览器下载
        exit;
    }
    /**
     * 库存预警
     */
    public function warn(){
        $today = date('Ymd',time());
        $status = 1;
        if(I('status')!==""){
            $status = I('status');
        }
        if(I('warn_batch')){
            $map['warn_batch'] = array("like","%".I('warn_batch')."%");
        }
        if(I('pname')){
            $map['pname'] = array("like","%".I('pname')."%");
        }
        if(I('BIN')){
            $map['BIN'] = array("like","%".I('BIN')."%");
        }
        if(I('warn_status')){
            switch (I('warn_status')){
                case 1:
                    $map['per2_time'] =array('egt',$today);
                    break;
                case 2:
                    $map['per2_time'] =array('lt',$today);
                    $map['per3_time'] =array('egt',$today);
                    break;
                case 3:
                    $map['per3_time'] =array('lt',$today);
                    break;
                default:
                    break;
            }
        }
        $map['status'] = $status;
        $list = $this->lists("Inventory_warn",$map);
        list_bin_array($list);
        $this->today = $today;
        $this->pname = I('pname');
        $this->warn_status = I('warn_status');
        $this->status = $status;
        $this->title = "库存预警";
        $this->assign("_list",$list);
        $this->display();
    }
    public function newcntwarn(){
        if(IS_POST){
            $model = M('Material_product');
            $rules = array(
                array('cnt_low', '/[0-9]+/','请输入纯数字' , 1 , 'regex' ,1),
                array('cnt_poor', '/[0-9]+/','请输入纯数字' , 1 , 'regex' ,1),
                array('cnt_much', '/[0-9]+/','请输入纯数字' , 1 , 'regex' ,1),
            );
            if(!$model->validate($rules)->create()){
                $this->error(M('Material_product')->getError());
            }else{
                $map['BIN'] = I('BIN');
                $data['cnt_low'] = I('cnt_low');
                $data['cnt_poor'] = I('cnt_poor');
                $data['cnt_much'] = I('cnt_much');
                if($model->where($map)->save($data)){
                    $this->success("设置成功");
                }else{
                    $this->error("设置失败");
                }
            }
        }else{
            if(I('BIN')==""){
                $this->error("信息不完全请重新点击链接",U('inventoryrealtime'));
                return false;
            }
            $this->BIN = I('BIN');
            $this->display();
        }

    }
    public function cntwarn(){
        $status = "";
        $map = array();
        if(I('BIN')!==""){
            $map['BIN'] = array('like','%'.I('BIN').'%');
        }
        if(I('pname')!==""){
            $map['pname'] = array('like','%'.I('pname').'%');
        }
        if(I('status')!==""){
            $status = I('status');
        }
        $model = M('vinventory');
        $res = $model->where($map)->select();
        $total = count($res);
        if (isset($REQUEST['r'])) {
            $listRows = (int) $REQUEST['r'];
        } else {
            $listRows = C('LIST_ROWS') > 0 ? C('LIST_ROWS') : 10;
        }
        $page = new \Think\Page($total, $listRows, $REQUEST);
        if ($total > $listRows) {
            $page->setConfig('theme', '%FIRST% %UP_PAGE% %LINK_PAGE% %DOWN_PAGE% %END% %HEADER%');
        }
        $p = $page->show();
        $classify = M('Material_classify')->where(array('status'=>1))->select();
        list_bin_array($res);
        get_cnt_warn($res,$status);
        $this->assign('_page', $p ? $p : '');
        $this->assign('_total', $total);
        $this->assign("_list",$res);
        $this->assign("_classify",$classify);
        $this->status = $status;
        $this->title = "实时库存";
        $this->display();
    }
    public function add_warn_days(){

        $id = I('id');
        $days = I('days');
        $res = M('Inventory_warn')->where(array('id'=>$id))->find();
        $data['per2_time'] = date("Ymd",strtotime('+'.$days.' day',strtotime($res['per2_time'])));
        $data['per3_time'] = date("Ymd",strtotime('+'.$days.' day',strtotime($res['per3_time'])));
        if(M('Inventory_warn')->where(array('id'=>$id))->save($data)){
            add_erp_log('Inventory','inventory_warn',$res['BIN'],'update','商品'.$res['BIN'].'延长天数'.$days);
            $this->success('修改成功');
        }

    }
    public function warnExport() {
        $today = date('Ymd',time());
        $where = "";
        if(I('status')==0){
            $where.=" and status = 0";
        }else{
            $where.=" and status = 1 ";
        }
        if(I('warn_batch')){
            $where.=" and warn_batch like '%".I('warn_batch')."%'";
        }
        if(I('pname')){
            $where.=" and pname like '%".I('pname')."%'";
        }
        if(I('BIN')){
            $where.=" and BIN like '%".I('BIN')."%'";
        }
        if(I('warn_status')){
            switch (I('warn_status')){
                case 1:
                    $where.=" and per2_time >= ".$today."";
                    break;
                case 2:
                    $where.=" and per2_time >= ".$today." and per2_time < ".$today."";
                    break;
                case 3:
                    $where.=" and per2_time < ".$today."";
                    break;
                default:
                    break;
            }
        }

        $sql = "select BIN,warn_batch,cnt, case when".
          " per2_time > ".$today." then '销售'".
         "when per3_time < ".$today." then '处理'".
         "else '榨汁' end, per2_time,per3_time from gr_inventory_warn  where 1=1 ".$where."";
        $Model = new Model();
        $data = $Model->query($sql);
        if ($data){
            add_erp_log('Inventory','inventory_warn','预警表','export','导出预警表');
            $i = 0;
             foreach($data as $key => $val){
                 array_splice($data[$i], 1,0,get_name_by_id($val['BIN'],'Material_product','BIN','pname'));
                 array_splice($data[$i], 2,0,get_name_by_id($val['BIN'],'Material_product','BIN','spec'));
                $i++;
             }
            //导入PHPExcel类库，因为PHPExcel没有用命名空间，只能inport导入
            import("Org.Util.PHPExcel");
            import("Org.Util.PHPExcel.Writer.Excel5");
            import("Org.Util.PHPExcel.IOFactory.php");

            $filename = "output_order_excel";

            $headArr = array("编码","商品名","规格","预警批次", "数量","预警状态","预估榨汁期","预估处理器");
            $title = "实时库存列表";
            $this->getExcel($filename, $headArr, $data, $title);
        }else{
            $this->error("没有可导出的数据！");
        }
    }
}
